package qst.com.bacK.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qst.com.bacK.exception.ExamException;
import qst.com.bacK.mapper.TestPersonnelMapper;
import qst.com.bacK.mapper.UserMapper;
import qst.com.bacK.pojo.entity.Team;
import qst.com.bacK.pojo.entity.TestPersonnel;
import qst.com.bacK.pojo.entity.User;
import qst.com.bacK.service.UserService;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * Author:   msh
 * Date:     2024/10/8 下午8:40
 * Description:
 */

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TestPersonnelMapper testPersonnelMapper;

    @Override
    public List<Team> showAllTeam() {
        return userMapper.findAllTeam();
    }

    @Override
    public User findUserByLoginCount(String loginCount) {
        return userMapper.findUserByLoginCount(loginCount);
    }

    @Override
    public void addTestPersonnel(TestPersonnel testPersonnel) {
        User u = testPersonnel.getUser();
        if (u.getType() == 0) {
            u.setType(4);
        }

        u.setStatus(1);
        if (u.getPasswd() == null || u.getPasswd().isEmpty()) {
            u.setPasswd(User.PASSWORD);
        }

        if (u.getLogin() == null) {
            u.setLogin(testPersonnel.getPhone());
        } else {
            testPersonnel.setPhone(u.getLogin());
        }

        userMapper.insert(u);
        User user = userMapper.findUserByLoginCount(u.getLogin());
        testPersonnel.setId(user.getId());
        try {
            testPersonnelMapper.insert(testPersonnel);
        } catch (SQLException e) {
            throw new ExamException("保存数据失败", e);
        }
    }

    @Override
    public User login(String login, String password) {
        User user = userMapper.findUserByLoginCount(login);
        String msg = "";
        if (user == null) {
            msg = "用户名不存在";
        } else if (!user.getPasswd().equals(password)) {
            msg = "密码错误";
        } else if (user.getStatus() == 0) {
            msg = "用户被禁用";
        }
        if (!msg.isEmpty()) {
            throw new ExamException(msg);
        }
        userMapper.updateLastLogin(user.getId(), new Timestamp(System.currentTimeMillis()));
        return user;
    }

    @Override
    public void updatePassword(Integer id, String oldPasswd, String newPasswd) {
        User user = userMapper.findUserByPassword(id);
        if (user.getPasswd().equals(oldPasswd)) {
            userMapper.updatePassword(id, newPasswd);
        } else {
            throw new ExamException("原密码错误");
        }
    }
}
